import React from 'react';
import { isForm } from '../constant/component-type';

class DynamicDatasource extends React.Component {
  static defaultProps = {
    datasource: {},
  };

  state = {
    datasource: undefined,
  };

  componentDidMount() {
    const { datasource } = this.props;
    if (datasource.type === 'dynamic') {
      console.log(datasource);
    }
  }

  render() {
    const { children, datasource = {} } = this.props;
    const { node } = children.props;
    if (datasource.type === 'static') {
      node.data.defaultValue = datasource.defaultValue;
      node.data.datasource = datasource.value;
    } else if (datasource.type === 'dynamic') {
      node.data.datasource = this.state.datasource;
    }
    return React.cloneElement(children, {
      ...children.props,
      node,
    });
  }
}

export default {
  strategy(props) {
    const { node } = props;
    return isForm(node.type);
  },
  component(props) {
    const {
      node: { data = {} },
      children,
    } = props;
    return (
      <DynamicDatasource datasource={data.datasource}>
        {children}
      </DynamicDatasource>
    );
  },
};
